package com.fuhe.chen.vendingmachine.common;

import com.fuhe.chen.vendingmachine.pojo.Commodity;
import com.fuhe.chen.vendingmachine.service.ICommodityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Utils {

    public static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);

    private static Map<Integer,Integer> pickCodeCounts = new HashMap<>();

    /**
     * 自动生成16位订单号
     *
     * @return
     */
    public static String getOrderIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String sequence = getFourRandom();

        String result = "FH";
        return result + newDate + sequence;
    }

    public static Boolean isCommodityOnSale(Integer commodity_id, ICommodityService commodityService) {
        List<Commodity> commodities = commodityService.queryAllOnSale();
        for (Commodity commodity : commodities) {
            if (commodity.getId().equals(commodity_id)) {
                return true;
            }
        }
        return false;
    }

    public static String getContainerFormatString(String str) {
        if (str.length() == 1) {
            return "0" + str;
        } else {
            return str;
        }
    }


    public static String getFourRandom() {
        Random random = new Random();
        String fourRandom = random.nextInt(1000000) + "";
        int randLength = fourRandom.length();
        if (randLength < 6) {
            for (int i = 1; i <= 6 - randLength; i++)
                fourRandom = "0" + fourRandom;
        }
        return fourRandom;
    }

    /**
     * Long类型时间->转换成日期->转成要求格式的String类型
     */
    public static String fromLongToDate(String format, Long time) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = new Date(time);
        return sdf.format(date);
    }

    /**
     * md5加密
     *
     * @param source 数据源
     * @return 加密字符串
     */
    public static String MD5encode(String source) {
        if (isBlank(source)) {
            return null;
        }
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ignored) {
        }
        byte[] encode = messageDigest.digest(source.getBytes());
        StringBuilder hexString = new StringBuilder();
        for (byte anEncode : encode) {
            String hex = Integer.toHexString(0xff & anEncode);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }


    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }


    /**
     * 接收上传文件并返回文件相对路径
     *
     * @param picture
     * @param imgPath
     * @return
     */
    public static String upload(MultipartFile picture, String imgPath) {
        if (picture == null) {
            return null;
        } else {
            try {
                String fileName = picture.getOriginalFilename();
                String filePath = "/mnt1/img/" + getDateIdByTime() + "/";
                File catalog = new File(filePath);
                catalog.setWritable(true, false);
                if (!catalog.exists()) {
                    catalog.mkdirs();
                    LOGGER.info("文件夹不存在,已经创建新文件夹:" + filePath);
                }
                File dest = new File(filePath + fileName);
                imgPath = filePath + fileName;
                picture.transferTo(dest);
                LOGGER.info("上传成功,文件路径:" + filePath + fileName);
                return imgPath;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return imgPath;
    }

    /**
     * 将Base64位编码的图片进行解码，并保存为指定文件名
     *
     * @param base64  base64编码的图片信息
     * @param imgName 文件名
     * @return
     */
    public static String decodeBase64ToImage(String base64,
                                             String imgPath,
                                             String imgName) {

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            String fileName = imgName + ".jpg";
//            String filePath = ResourceUtils.getURL("classpath:static").getPath().replace("%20"," ").replace('/', '\\')+"/img/"+getDateIdByTime()+"/";
            String filePath = "/mnt1/img/" + getDateIdByTime() + "/";

            File catalog = new File(filePath);
            catalog.setWritable(true, false);
            if (!catalog.exists()) {
                catalog.mkdirs();
                LOGGER.info("文件夹不存在,已经创建新文件夹:" + filePath);
            }
            File dest = new File(filePath + fileName);
            dest.setWritable(true, false);
            imgPath = filePath + fileName;
            FileOutputStream write = new FileOutputStream(dest);
            byte[] decoderBytes = decoder.decodeBuffer(base64);
            write.write(decoderBytes);
            write.close();
            return imgPath;
        } catch (IOException e) {
            e.printStackTrace();
            return "#";
        }

    }

    public static String getBase64(String bgImage) {
        return bgImage.replace("url(\"", "").replace("\")", "").replace("data:image/jpeg;base64,", "");
    }

    public static String getDateIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String newDate = sdf.format(new Date());

        return newDate;
    }

    /**
     * 分割商品编号字符串
     *
     * @param ids
     * @return
     */
    public static List<String> getOrders(String ids) {
        String[] strs = ids.split(",");
        List list = Arrays.asList(strs);
        return list;
    }

    /**
     * 将"yyyy-MM-dd"字符串转化为开始或结束时间(LONG)
     *
     * @param date
     * @param name
     * @return
     */
    public static Long getTime(String date, String name) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (name.equals("start")) {
                Long returnNum = sdf.parse(date).getTime();
                LOGGER.info("开始时间:" + returnNum);
                return returnNum;
            }
            if (name.equals("end")) {
                Date end = sdf.parse(date);
                Calendar c = Calendar.getInstance();
                c.setTime(end);
                c.add(Calendar.DAY_OF_MONTH, 1);
                Long returnNum = c.getTime().getTime();
                LOGGER.info("结束时间:" + returnNum);
                return returnNum;
            }
        } catch (Exception e) {
            LOGGER.info("字符串转换时间失败");
            e.printStackTrace();
        }
        return null;
    }

    public static String getMonthByString(String month) {
        switch (month) {
            case "01":
                return "一月";
            case "02":
                return "二月";
            case "03":
                return "三月";
            case "04":
                return "四月";
            case "05":
                return "五月";
            case "06":
                return "六月";
            case "07":
                return "七月";
            case "08":
                return "八月";
            case "09":
                return "九月";
            case "10":
                return "十月";
            case "11":
                return "十一月";
            case "12":
                return "十二月";
        }
        return null;
    }

    //生成机器取货码
    public static String getPickCode(String containerNumber) {
        SimpleDateFormat sdf = new SimpleDateFormat("mmss");
        String newDate = sdf.format(new Date());

        return newDate + containerNumber;
    }

    //生成门店取货码
    //当前秒数 + 取货数(计数最高为9999,超过则清零)
    public static String getStorePickCode(Integer machineID) {
        SimpleDateFormat sdf = new SimpleDateFormat("ss");
        String newDate = sdf.format(new Date());

        return newDate + getCodeCount(machineID);
    }

    //获取取货计数器结果
    private static String getCodeCount(Integer machineID) {
        Integer count = pickCodeCounts.get(machineID);
        if(count==null){
            count = 0;
        }
        count++;
        if (count > 9999) {
            count = 1;
        }
        String result = String.valueOf(count);
        switch (result.length()) {
            case 1:
                result = "000" + result;
                break;
            case 2:
                result = "00" + result;
                break;
            case 3:
                result = "0" + result;
                break;
        }
        pickCodeCounts.put(machineID,count);
        return result;
    }
}